import { defineStore } from "pinia"
import { BasicPageSearch } from '@/models/basicType'
import { MyMaterialOverview, MyMaterialPageResult } from "@/models/material"
import { materialApi } from "@/services"
import { toast } from "vue3-toastify"

const useMyMaterialStore  = defineStore('MyMaterial', {
    // state
    state:() =>({
        pageSize: 10,
        pageNum: 1,
        totalRecords: 0,
        myMaterialOverview: {} as MyMaterialOverview,
        myMaterialPageResult: {} as MyMaterialPageResult,
    }),

    // actions
    actions:{
        // 获取我的资料概览
        async getMyMaterialOverview() {
            try {
                const res = await materialApi.getMyOverview()
                this.myMaterialOverview = res? res : {} as MyMaterialOverview
            } catch(err) {
                toast.error('获取我的资料概览出现异常：'+ err);
            }
        },

        // 获取我的资料列表（分页）
        async getMyMaterials(pageSize: number, pageNum: number) {
            try {
                const data : BasicPageSearch = {
                    pageSize: pageSize,
                    pageNum: pageNum
                };
                const res = await materialApi.getMyMaterials(data)
                this.myMaterialPageResult = res? res : {} as MyMaterialPageResult
                this.totalRecords = this.myMaterialPageResult.count
            } catch(err) {
                toast.error('获取我的资料列表出现异常：'+ err);
            }
        },

        // 删除我的资料（支持批量）
        async deleteMyMaterials(ids:number[]) {
            try {
                const res = await materialApi.deleteMyMaterials(ids)
                if (res && res.result) {
                    this.refreshData()
                }
            } catch(err) {
                toast.error('删除我的资料出现异常：'+ err);
            }
        },
        
        // 初始化数据
        async initData() {
            await this.getMyMaterialOverview()
            await this.refreshData();
        },

        // 刷新数据（在当前页）
        async refreshData(){
            await this.getMyMaterials(this.pageSize,this.pageNum)
        },

        // 开始查询
        async handleSearch(){      
            await this.getMyMaterials(this.pageSize,1)
        },

        async handlePageChange(pageNum:number,pageSize:number){     
            this.pageNum = pageNum
            this.pageSize = pageSize   
            this.refreshData()
        }
    },
    getters:{
        myOverview:(state) => state.myMaterialOverview,
        materialSource:(state) => state.myMaterialPageResult.records,
    }
})

export default useMyMaterialStore;